package com.renli.controller;

import com.renli.bean.ResultJson;

import com.renli.pojo.*;
import com.renli.service.RecruitService;
import com.renli.vo.InterviewVo;
import com.renli.vo.SelectPostRelease;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.apache.poi.POIXMLException;


import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;


import java.text.SimpleDateFormat;
import java.util.*;


//招聘接口
@Controller
@Api(value = "招聘管理接口test", tags = "招聘管理接口API")
@ResponseBody
public class RecruitController {
    @Autowired
    RecruitService recruitService;

    @RequestMapping(value = "/insertPostRelease", method = RequestMethod.POST)
    @ApiOperation(value = "添加职位发布表接口", notes = "传职位发布数据进行添加", httpMethod = "post", response = ResultJson.class)
    public ResultJson insertPostRelease(@RequestBody @ApiParam(name = "postRelease", value = "职位发布表信息", required = true) PostRelease postRelease) {

        return recruitService.insertPostRelease(postRelease);
    }

    @RequestMapping(value = "/selectPostRelease", method = RequestMethod.POST)
    @ApiOperation(value = "遍历及查询职位发布表接口", notes = "遍历职位发布表", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectPostRelease(@RequestBody @ApiParam(name = "查询的参数", value = "查询的参数(creatTime,deadTime,postName,postClassId,id)", required = false) SelectPostRelease selectPostRelease) {

        return recruitService.selectPostRelease(selectPostRelease);
    }


    @RequestMapping(value = "/selectDepartment", method = RequestMethod.POST)
    @ApiOperation(value = "遍历部门的接口", notes = "遍历部门", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectDepartment() {
        return recruitService.selectAllDepartment();
    }

    @RequestMapping(value = "/selectPost", method = RequestMethod.POST)
    @ApiOperation(value = "遍历和查询职位的接口", notes = "遍历和查询职位", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectPost(@RequestBody @ApiParam(name = "post", value = "部门id 或 职位dep_id", required = false) Post post) {
        return recruitService.selectPost(post);
    }

    @RequestMapping(value = "/selectPostClass", method = RequestMethod.POST)
    @ApiOperation(value = "遍历职位类型的接口", notes = "遍历职位类型", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectPostClass() {
        return recruitService.selectPostClass();
    }

    @RequestMapping(value = "/updatePostRelease", method = RequestMethod.POST)
    @ApiOperation(value = "变更（修改）职位发布表接口", notes = "传职位发布数据进行修改", httpMethod = "post", response = ResultJson.class)
    public ResultJson updatePostRelease(@RequestBody @ApiParam(name = "postRelease", value = "职位发布表信息", required = true) PostRelease postRelease) {

        return recruitService.updatePostRelease(postRelease);
    }

    @RequestMapping(value = "/insertResume", method = RequestMethod.POST)
    @ApiOperation(value = "简历上传接口", notes = "简历上传读取", httpMethod = "post", response = ResultJson.class)
    public ResultJson insertResume( @ApiParam(name = "resume", value = "简历信息", required = true) Resume resume,
            @ApiParam(name = "doc", value = "简历word文档", required = false) MultipartFile file,
                                    HttpServletRequest request) {
        if (file==null){return recruitService.insertResume(resume);}

        else {
        ResultJson resultJson=new ResultJson();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String res = sdf.format(new Date());
        String name=resume.getRealName();
        // uploads文件夹位置
        String rootPath = request.getSession().getServletContext().getRealPath("download/");
        // 原始名称
        String originalFileName = file.getOriginalFilename();
        String substring = originalFileName.substring(originalFileName.lastIndexOf("."));//后缀名
        if (substring.equals(".doc")||substring.equals(".docx")){
        // 新文件名
        String newFileName = name + res + substring;
        // 创建年月文件夹
        Calendar date = Calendar.getInstance();
        File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));

        // 新文件
        File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
        // 判断目标文件所在目录是否存在
        if (!newFile.getParentFile().exists()) {
            // 如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }


            // 将内存中的数据写入磁盘
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }


            resume.setEnclosureurl( "download"+ File.separator + dateDirs + File.separator + newFileName);
            System.out.println( "download"+ File.separator + dateDirs + File.separator + newFileName);
             return recruitService.insertResume(resume);
        }
        else {
             return resultJson.setFail("添加失败,简历文件格式错误");
        }}
    }

    @RequestMapping(value = "/updateResume", method = RequestMethod.POST)
    @ApiOperation(value = "简历修改接口", notes = "简历修改", httpMethod = "post", response = ResultJson.class)
    public ResultJson updateResume( @ApiParam(name = "resume", value = "简历信息", required = true) Resume resume,
                                    @ApiParam(name = "doc", value = "简历word文档", required = false) MultipartFile file,
                                    HttpServletRequest request) {
        if (file==null){return recruitService.insertResume(resume);}

        else {
            ResultJson resultJson=new ResultJson();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
            String res = sdf.format(new Date());
            String name=resume.getRealName();
            // uploads文件夹位置
            String rootPath = request.getSession().getServletContext().getRealPath("download/");
            // 原始名称
            String originalFileName = file.getOriginalFilename();
            String substring = originalFileName.substring(originalFileName.lastIndexOf("."));//后缀名
            if (substring.equals(".doc")||substring.equals(".docx")){
                // 新文件名
                String newFileName = name + res + substring;
                // 创建年月文件夹
                Calendar date = Calendar.getInstance();
                File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));

                // 新文件
                File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
                // 判断目标文件所在目录是否存在
                if (!newFile.getParentFile().exists()) {
                    // 如果目标文件所在的目录不存在，则创建父目录
                    newFile.getParentFile().mkdirs();
                }


                // 将内存中的数据写入磁盘
                try {
                    file.transferTo(newFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }


                resume.setEnclosureurl( "download"+ File.separator + dateDirs + File.separator + newFileName);
                System.out.println( "download"+ File.separator + dateDirs + File.separator + newFileName);
                return recruitService.updateResume(resume);
            }
            else {
                return resultJson.setFail("修改失败,简历文件格式错误");
            }}
    }

    @RequestMapping(value = "/redWordUpload", method = RequestMethod.POST)
    @ApiOperation(value = "word识别接口接口", notes = "识别上传文件", httpMethod = "post", response = ResultJson.class)
    public ResultJson redWordPostRelease(@ApiParam(name = "doc", value = "简历word文档", required = true) MultipartFile file, HttpServletRequest request) {
        ResultJson<Object> resultJson = new ResultJson<>();
        InputStream inputStream = null;
        Map<String, Object> map = new HashMap<>();

        try {
            inputStream = file.getInputStream();//获取前端传递过来的文件对象，存储在“inputStream”中
            String fileName = file.getOriginalFilename();//获取文件名
            System.out.println(fileName);
            XWPFDocument doc = null; //用于存储解析后的Excel文件

            //判断文件扩展名为“.xls还是xlsx的Excel文件”,因为不同扩展名的Excel所用到的解析方法不同
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            if (".docx".equals(fileType)||".doc".equals(fileType)) {
                Workbook workbook = null;
                Iterator<XWPFTable> itTable=null;
                try {
                    doc = new XWPFDocument(inputStream);//HSSFWorkbook专门解析.xls文件
                    itTable = doc.getTablesIterator();
                } catch (POIXMLException e) {
                    e.printStackTrace();
                    resultJson.setFail("失败，文件格式错误");
                    return resultJson;
                }


                System.out.println(itTable.hasNext());
                int ind = 0;

                while (itTable.hasNext()) {
                    ind++;
                    XWPFTable table = (XWPFTable) itTable.next();
                    //行
                    int rcount = table.getNumberOfRows();
                    for (int i = 0; i < rcount; i++) {
                        XWPFTableRow row = table.getRow(i);
                        //列
                        List<XWPFTableCell> cells = row.getTableCells();
                        int len = cells.size();
                        for (int j = 0; j < len; j++) {
                            XWPFTableCell xc = cells.get(j);
                            String sc = xc.getText();
                            System.out.println("第" + ind + "个表格，第" + (i + 1) + "行，第" + (j + 1) + "列：" + sc);
                            if (i == 0 && j == 1) {
                                map.put("realName", sc);
                            }
                            if (i == 0 && j == 3) {
                                map.put("gender", sc);
                            }
                            if (i == 0 && j == 5) {

                                map.put("birth ", sc);


                            }
                            if (i == 1 && j == 1) {
                                map.put("censusRegister", sc);
                            }
                            if (i == 1 && j == 3) {
                                map.put("education", sc);
                            }
                            if (i == 1 && j == 5) {

                                map.put("logTime", sc);}
                            if (i == 2 && j == 1) {
                                map.put("politicsStatus", sc);
                            }
                            if (i == 2 && j == 3) {
                                map.put("workDate", sc);
                            }
                            if (i == 2 && j == 5) {
                                map.put("postName", sc);
                            }
                            if (i == 3 && j == 1) {
                                map.put("isWorker", sc);
                            }
                            if (i == 3 && j == 3) {
                                map.put("isStudent", sc);
                            }
                            if (i == 4 && j == 1) {
                                map.put("major", sc);
                            }
                            if (i == 4 && j == 3) {
                                map.put("idCard", sc);
                            }
                            if (i == 5 && j == 1) {
                                map.put("graduation", sc);
                            }
                            if (i == 5 && j == 3) {
                                map.put("phone", sc);
                            }
                            if (i == 6 && j == 1) {
                                map.put("email", sc);
                            }
                            if (i == 6 && j == 3) {
                                double dreamMoney = Double.parseDouble(sc);
                                map.put("dreamMoney", dreamMoney);
                            }
                            if (i == 7 && j == 1) {
                                map.put("myResume", sc);
                            }


                        }
                    }
                }
                resultJson.setSuccess("成功", map);
                return resultJson;
            } else {
                resultJson.setFail("失败，文件格式错误");
                return resultJson;
            }



        } catch (IOException e) {
            e.printStackTrace();
            resultJson.setFail("未知错误,失败");
            return resultJson;
        }
        finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @RequestMapping(value = "/selectResume", method = RequestMethod.POST)
    @ApiOperation(value = "遍历所有简历信息", notes = "查询简历（遍历）", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectResume(@RequestBody @ApiParam(name = "resume", value = "简历信息", required = false) Resume resume
                                   ) {
            return recruitService.selectResume(resume);
    }

    @RequestMapping(value = "/selectInterviewResume", method = RequestMethod.POST)
    @ApiOperation(value = "遍历所有面试的简历信息", notes = "查询正在面试的简历（遍历）", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectInterviewResume(@RequestBody @ApiParam(name = "resume", value = "简历信息(查询的条件)", required = false) Resume resume
    ) {
        return recruitService.selectInterviewResume(resume);
    }

    @RequestMapping(value = "/selectOneResume", method = RequestMethod.POST)
    @ApiOperation(value = "查询单个简历", notes = "查询简历详情（包括改简历面试信息）", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectResume(@RequestBody @ApiParam(name = "resumeId", value = "当前简历的ID(resumeId)", required = true) Map<String,Integer> map
                                   ) {
        return recruitService.selectOneResume(map);
    }
    @RequestMapping(value = "/insertInterview", method = RequestMethod.POST)
    @ApiOperation(value = "面试登记", notes = "登记面试的信息", httpMethod = "post", response = ResultJson.class)
    public ResultJson insertInterview(@RequestBody @ApiParam(name = "InterviewVo", value = "评论，当前user，时间为当前日期,简历id", required = true)InterviewVo interviewVo){
        return  recruitService.insertInterview(interviewVo);
    }
    @RequestMapping(value = "/delectInterview", method = RequestMethod.POST)
    @ApiOperation(value = "面试登记,面试不通过", notes = "面试不通过，删除简历和面试信息", httpMethod = "post", response = ResultJson.class)
    public ResultJson delectInterview(@RequestBody @ApiParam(name = "InterviewVo", value = "评论，当前user，时间为当前日期,简历id", required = true)InterviewVo interviewVo){
        return  recruitService.delectInterview(interviewVo);
    }
}